<template>
  <div class="app-container" style="padding:1vh 4vw">
    <el-row class="filter-container" style="margin: 6vh 2vw;">
      <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
        <el-container direction="horizontal">
          <el-input
            v-model="query"
            class="filter-item"
            clearable
            placeholder="输入关键字搜索"
            prefix-icon="el-icon-search"
            style="width: 80%;"
            @keyup.enter.native="handleFilter"
          />
          <button v-show="device() !== 'mobile'" class="button" type="button" style="margin-left: 1vw"
                  @click="handleDownload"
          >
            <span class="button__text">导出Excel</span>
            <span class="button__icon"><svg id="bdd05811-e15d-428c-bb53-8661459f9307" xmlns="http://www.w3.org/2000/svg"
                                            viewBox="0 0 35 35" data-name="Layer 2" class="svg"
            ><path
              d="M17.5,22.131a1.249,1.249,0,0,1-1.25-1.25V2.187a1.25,1.25,0,0,1,2.5,0V20.881A1.25,1.25,0,0,1,17.5,22.131Z"
            /><path
              d="M17.5,22.693a3.189,3.189,0,0,1-2.262-.936L8.487,15.006a1.249,1.249,0,0,1,1.767-1.767l6.751,6.751a.7.7,0,0,0,.99,0l6.751-6.751a1.25,1.25,0,0,1,1.768,1.767l-6.752,6.751A3.191,3.191,0,0,1,17.5,22.693Z"
            /><path
              d="M31.436,34.063H3.564A3.318,3.318,0,0,1,.25,30.749V22.011a1.25,1.25,0,0,1,2.5,0v8.738a.815.815,0,0,0,.814.814H31.436a.815.815,0,0,0,.814-.814V22.011a1.25,1.25,0,1,1,2.5,0v8.738A3.318,3.318,0,0,1,31.436,34.063Z"
            /></svg></span>
          </button>
        </el-container>
      </el-col>
    </el-row>

    <el-dialog :visible.sync="dialogVisible" width="35%" style="margin-top: 15vh" :close-on-click-modal="false"
               :show-close="false" :fullscreen="device() === 'mobile'"
    >
      <!--      <el-progress type="line" :percentage="percentage" :text-inside="true" :stroke-width="20" :color="customColors" style="margin-left: 1rem;margin-right: 1rem" />-->
      <div class="tip">
        正在导出下载中....
        <!--        <br>请不要切换/关闭本页面-->
      </div>
    </el-dialog>

    <div class="tab-container" style="margin: 1vh 2vw;">
      <el-tabs v-model="activeName" type="border-card">
        <el-tab-pane v-for="item in tabMapOptions" :key="item.key" :label="item.label" :name="item.key">
          <span slot="label"><i :class="item.key === 'enroll' ? 'el-icon-date' : 'el-icon-edit-outline'"/>
            {{ item.label }}
          </span>
          <h2 align="center" style="line-height: 33px;font-size: 20px;font-family: Source Han Sans CN, PingFang SC, Helvetica Neue, Helvetica, Hiragino Sans GB, Microsoft YaHei, 微软雅黑, Arial, sans-serif">
            {{ activityTitle }} {{ item.title }}
          </h2>
          <el-table :data="item.key === 'enroll' ? enrollsList : entersList" border highlight-current-row :size="handleSize()" style="width: 100%;" max-height="800">
            <el-table-column label="学号" max-width="400" min-width="150">
              <template v-slot="scope">
                <span>{{ scope.row.number }}</span>
              </template>
            </el-table-column>
            <el-table-column label="姓名" max-width="200" min-width="100">
              <template v-slot="scope">
                <span>{{ scope.row.name }}</span>
              </template>
            </el-table-column>
            <el-table-column label="学院" max-width="400" min-width="150">
              <template v-slot="scope">
                <span>{{ scope.row.college }}</span>
              </template>
            </el-table-column>
            <el-table-column label="时间" max-width="400" min-width="150">
              <template v-slot="scope">
                <span>{{ formatToDatetime(scope.row.createdAt) }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import { indexActivityUser } from '@/api/base/activityUser'
import { exportExcel } from '@/api/admin/activity'
import { itemActivity } from '@/api/user/activity'
import { itemUser } from '@/api/admin/user'
import axios from 'axios'

export default {
  data() {
    return {
      query: '',
      currentPage: 1,
      lastPage: 0,
      total: 0,
      perPage: 0,
      // percentage: 0,
      // guid: '',
      activeName: 'enroll',
      dialogVisible: false,
      tabMapOptions: [
        { label: '报名记录', key: 'enroll', title: '报名名单' },
        { label: '与会记录', key: 'enter', title: '参加名单' }],
      activityId: 0,
      activityTitle: undefined,
      enrollsList: [],
      entersList: []
      // customColors: [
      //   { color: '#f56c6c', percentage: 20 },
      //   { color: '#e6a23c', percentage: 40 },
      //   { color: '#5cb87a', percentage: 60 },
      //   { color: '#1989fa', percentage: 80 },
      //   { color: '#6f7ad3', percentage: 100 }
      // ]
    }
  },
  watch: {
    // 监听路由变化
    activeName(val) {
      this.$router.push(`${this.$route.path}?tab=${val}`)
    }
  },
  created() {
    // 初始化默认选定选项卡
    const tab = this.$route.query.tab
    if (tab) {
      this.activeName = tab
    }
    // 获取当前页活动id
    this.activityId = this.$route.query.id
    // 从服务器获取 活动记录
    this.currentPage = 1
    this.getActivityUser()
  },
  methods: {
    // 获取活动 报名记录 和 签到记录
    async getActivityUser() {
      // 获取报名记录
      const enrollRes = await indexActivityUser({ page: this.currentPage, status: 0, activity_id: this.activityId })
      let enrollsList = enrollRes.data.data
      // console.log(enrollsList)
      for (const enrollsListKey in enrollsList) {
        const resUser = await itemUser({ id: enrollsList[enrollsListKey].userId })
        enrollsList[enrollsListKey]['name'] = resUser.data.name
        enrollsList[enrollsListKey]['number'] = resUser.data.number
        enrollsList[enrollsListKey]['college'] = resUser.data.college
      }
      this.enrollsList = enrollsList

      // 获取签到记录
      const enterRes = await indexActivityUser({ page: this.currentPage, status: 1, activity_id: this.activityId })
      let entersList = enterRes.data.data
      for (const entersListKey in entersList) {
        const resUserEnter = await itemUser({ id: enrollsList[entersListKey].userId })
        entersList[entersListKey]['name'] = resUserEnter.data.name
        entersList[entersListKey]['number'] = resUserEnter.data.number
        entersList[entersListKey]['college'] = resUserEnter.data.college
      }
      this.entersList = entersList

      // 获取活动标题
      const titleRes = await itemActivity({ id: this.activityId })
      this.activityTitle = titleRes.data.title
    },
    // 导出Excel
    async handleDownload() {
      this.dialogVisible = true
      const title = this.activityTitle;
      const titleStatus = this.activeName === 'enroll' ? '报名名单' : '签到名单'
      const status = this.activeName === 'enroll' ? 0 : 1
      // , status: status
      exportExcel({ id: this.activityId })
        .then((res) => {
          //console.log(res, this.activityId, '请求下载数据')
          const blob = new Blob([res]);
          const url = window.URL.createObjectURL(blob)
          const link = document.createElement('a')
          link.href = url
          link.setAttribute('download',title + titleStatus + ".xlsx");
          document.body.appendChild(link)
          link.click()
        }).catch((e) => {
        console.log(e)
        this.$notify({
          title: '失败',
          message: '下载失败',
          type: 'error',
          duration: 2000
        })
      })
      await this.sleep(2000)
      this.dialogVisible = false
    },
    // 返回设备类别
    device() {
      return this.$store.state.app.device
    },
    // 根据设备类型控制尺寸
    handleSize() {
      return this.$store.state.app.device === 'mobile' ? 'mini' : 'medium'
    },
    // 换页
    change(e) {
      this.currentPage = e
      this.getActivities()
    },
    // 时间戳 转换为 时间单位
    timestampToTime(timestamp) {
      const date = new Date(timestamp)
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')
      const seconds = date.getSeconds().toString().padStart(2, '0')

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    // 时间格式化方法
    formatToDatetime(isoString) {
      const date = new Date(isoString)
      if (isNaN(date.getTime())) {
        throw new Error('Invalid ISO 8601 date string')
      }
      const year = date.getFullYear()
      const month = (1 + date.getMonth()).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')
      const seconds = date.getSeconds().toString().padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    // 搜索
    handleFilter() {
      const currentPage = this.currentPage
      const query = this.query
      let status
      if (this.activeName === 'enroll') {
        status = 0
      } else {
        status = 1
      }
      const res = indexActivityUser({ params: { currentPage, query, status } })
      this.activeName === 'enroll' ? this.enrollsList = res.data.data : this.entersList = res.data.data
      // this.currentPage = res.data.currentPage
      // this.lastPage = res.data.lastPage
      // this.total = res.data.total
      // this.perPage = res.data.perPage
    },
    sleep(ms) {
      return new Promise(resolve => setTimeout(resolve, ms))
    }
  }
}
</script>

<style scoped lang="scss">
.app-container {
  //margin-top: 30px;
  //margin-left: 2rem;
  //margin-right: 2rem;
  //border-radius: 15px;
  //box-shadow: 0 1px 4px rgba(0, 0, 0, 0.4);

  .filter-container {
    //margin-right: 30px;
    //margin-left: 30px;
    //margin-top: 30px;
  }

  .tab-container {
    .h2 {
      //font-weight: 500;
    }
  }

  .tip {
    font-size: 20px;
    margin-top: 30px;
    text-align: center;
    color: #ff6600;
  }
}

.button {
  position: relative;
  width: 150px;
  height: 40px;
  cursor: pointer;
  display: flex;
  align-items: center;
  //border: 1px solid #0078E8;
  border: 1px solid #409EFF;
  border-radius: 5px;
  background-color: #409EFF;
  //background-color: #0082FC;
  overflow: hidden;
}

.button, .button__icon, .button__text {
  transition: all 0.3s;
}

.button .button__text {
  transform: translateX(30px);
  color: #fff;
  font-weight: 550;
}

.button .button__icon {
  position: absolute;
  transform: translateX(109px);
  height: 100%;
  width: 39px;
  background-color: #0078E8;
  display: flex;
  align-items: center;
  justify-content: center;
}

.button .svg {
  width: 20px;
  fill: #fff;
}

.button:hover {
  background: #0078E8;
}

.button:hover .button__text {
  color: transparent;
}

.button:hover .button__icon {
  width: 148px;
  transform: translateX(0);
}

.button:active .button__icon {
  background-color: #0077C2;
}

.button:active {
  border: 1px solid #0077C2;
}

</style>
